1
大概是这样的,现在需要根据一下上传的图片以及一些输入生成图片。本来打算用imagemagick的,但是后来觉得这样前后端要搞两份不同的代码,然后imagemagick使用起来远没有canvas用起来顺手啊。So,最终决定就用Canvas搞定它了,然后通过toDataURL将图片的base64编码传回后端再保存。下面直接上代码。

<!DOCTYPE html>
<html>
<body>
    <img src="http://example.com/xxx.jpg"  id="pic"  style="display:none"/>
    <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");

        // 参见[Drawing_DOM_objects_into_a_canvas][1]
        function drawHtmlToCanvas() {
            var data = "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
             "<foreignObject width='100%' height='100%'>" +
               "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" +
                 "<em>I</em> like <span style='color:white; text-shadow:0 0 2px blue;'>cheese</span>" +
               "</div>" +
             "</foreignObject>" +
           "</svg>";
            var DOMURL = self.URL || self.webkitURL || self;
            var img = new Image();
            var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
            var url = DOMURL.createObjectURL(svg);
            img.onload = function() {
                ctx.drawImage(img, 0, 0);
                DOMURL.revokeObjectURL(url);
                // chrome版本不支持,目前只支持firefox
                console.log(canvas.toDataURL());
            };
            img.src = url;
        }

        function drawCrossOriginImg2Canvas(callback) {
            var img = new Image();
            // toDataURL存在跨域问题,参见[CORS Enabled Image][2],此处的图片服务器要支持Access-Control-Allow-Origin
            img.crossOrigin = "Anonymous";
            img.src = document.getElementById('pic').src;
            img.onload = function(){
                ctx.drawImage(img, 0, 0);
                callback && callback();
                // chrome&firefox 都OK
                console.log(canvas.toDataURL());
            }
        }

        drawCrossOriginImg2Canvas(drawHtmlToCanvas);

    </script>
</body>
</html>

有疑问的是问什么chrome为何对于blob:不支持toDataURL()

[1]: https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas
[2]: https://developer.mozilla.org/zh-CN/docs/CORS_Enabled_Image


moohyeah
81 声望1 粉丝